//
//  NetworkTools.swift
//  Weobo
//
//  Created by 史亚洲 on 16/1/20.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import AFNetworking

//定义枚举,在swift中,枚举可以定义任何类型
enum HTTPMethds: String {
    case POST = "POST"
    case GET = "GET"

}

private let hostName = "https://api.weibo.com/"
//private let hostName = "https://test.weibo.com/"错误的网址

//使用网络请求,单例对象
private let WBDomain = "com.weibo.data.error"

class NetworkTools: AFHTTPSessionManager {
    
    //1.网路请求单例对象
    static let sharedTools: NetworkTools = {
    
        
        //一个完整的网址:baseURL + 接口名称
       
        let url = NSURL(string: hostName)
        let tools = NetworkTools(baseURL: url)
        
        //设置反序列化支持的格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    
    }()
    
    //设置一个网络请求的核心方法,以后所有的网络请求都可以通过这个方法和AFNetworking直接联系
    func requestJSONDict(method: HTTPMethds,urlString: String,parameters: [String: AnyObject]?,finished: (dict: [String: AnyObject]?,error: NSError?) ->()) {
        
        if method == HTTPMethds.POST{
        
        POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            print(result)
            //类型转换将anyObject对象转化为[Key:Value]
            guard let dict = result as? [String : AnyObject] else {
            
                  print("数据格式不合法")
                /*
                1.执行失败的回调
                2.domain:域
                3.code:自定义error,使用负数
                */
                let myError = NSError(domain: WBDomain, code: -10000, userInfo:[NSLocalizedDescriptionKey: "数据格式不合法"])
                finished(dict: nil, error: myError)
                return
            
            }
            
            //程序走到这里表示一定可以得到字典类型结果,执行回调将数据回调到调用层
            finished(dict: dict, error: nil)
            
            
            }) { (_, error) -> Void in
                
                //请求失败
                finished(dict: nil, error: error)
                print(error)
           }

        } else {
            GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                print(result)
                //类型转换
                guard let dict = result as? [String : AnyObject] else {
                    print("数据格式不合法")
                    let myError = NSError(domain: WBDomain, code: -1000000, userInfo: [NSLocalizedDescriptionKey: "数据格式不合法"])
                    
                    finished(dict: nil, error: myError)
                    return

                }
                finished(dict: dict, error: nil)
                
                
                
                }, failure: { (_, error) -> Void in
                    
                    //请求失败
                    finished(dict: nil, error: error)

                    print(error)
            })

        
        }
    }

}
